package com.lost.octopus.es.helper.config;

import com.lost.octopus.es.helper.builder.FieldMatchBuilders;
import com.lost.octopus.es.helper.entity.query.highlight.HighlightDeal;
import com.lost.octopus.es.helper.entity.query.highlight.SimpleFileHighlightDeal;
import com.lost.octopus.es.helper.service.DocumentEsService;
import com.lost.octopus.es.helper.service.DocumentEsServiceImpl;

import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.elasticsearch.ElasticsearchRestClientProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.elasticsearch.config.AbstractElasticsearchConfiguration;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;

import lombok.extern.log4j.Log4j2;

/**
 * 初始化es
 * @author zhangbh
 **/
@Log4j2
@Configuration
@ConditionalOnClass({ElasticsearchRestClientProperties.class, AbstractElasticsearchConfiguration.class})
@EnableConfigurationProperties({ElasticsearchRestClientProperties.class})
@ComponentScan(value = "com.lost.octopus.es.helper")
@AutoConfigureAfter({AbstractElasticsearchConfiguration.class})
public class ElasticSearchConfig {

    @Bean
    @ConditionalOnMissingBean(DocumentEsService.class)
    public DocumentEsService baseEsService() {
        return new DocumentEsServiceImpl();
    }

    @Bean
    @ConditionalOnBean(RestHighLevelClient.class)
    @ConditionalOnMissingBean(ElasticsearchRestTemplate.class)
    public ElasticsearchRestTemplate elasticsearchRestTemplate(RestHighLevelClient client) {
        return new ElasticsearchRestTemplate(client);
    }

    @Bean
    @ConditionalOnMissingBean(FieldMatchBuilders.class)
    public FieldMatchBuilders fieldMatchBuilders() {
        return new FieldMatchBuilders();
    }

    /**
     * 高亮转换配置
     * @return 高亮配置对象
     */
    @Bean
    @ConditionalOnMissingBean(HighlightDeal.class)
    public HighlightDeal highlightDeal() {
        return new SimpleFileHighlightDeal();
    }

    /**
     * es 请求选项
     * @return 请求选项
     */
    @Bean
    @ConditionalOnMissingBean(RequestOptions.class)
    public RequestOptions requestOptions() {
        return RequestOptions.DEFAULT.toBuilder().build();
    }
}
